// 云函数入口文件
const cloud = require('wx-server-sdk')
const fs = require('fs')
const path = require('path')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let custom = event.custom;
  let openid = wxContext.OPENID;
  let fileContent = event.fileContent;
  let goods_name = event.goods_name;
  let specs = event.specs;
  let type = event.type;
  let goods_explain = event.goods_explain;
  let goods_url = event.goods_url;
  let cloudPath = "goods_image/" + openid + Date.now() + ".jpg";
  let update_time = new Date();
  let fileID = '';
  if (custom == false) {
    fileID = goods_url;
  } else {
    let res = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: new Buffer(fileContent, 'base64'),
    });
    fileID = res.fileID;
  }
  try {
    return await db.collection('ops_goods').add({
      data: {
        Issuer_openid: openid,
        goods_name: goods_name,
        specs: specs,
        type: type,
        goods_explain: goods_explain,
        goods_url: fileID,
        status: 1,
        update_time: update_time
      }
    });
  } catch (error) {
    console.log(error);
  }
}